package com.wysql.ascost.controller.info;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wysql.ascost.common.base.BaseController;
import com.wysql.ascost.common.domain.AjaxResult;
import com.wysql.ascost.common.domain.ResultTable;
import com.wysql.ascost.model.custom.Tablepar;
import com.wysql.ascost.model.info.InfoFile;
import com.wysql.ascost.model.info.InfoFileExample;
import com.wysql.ascost.model.info.InfoProjectbudget;
import com.wysql.ascost.service.info.InfoFileService;
import com.wysql.ascost.service.info.InfoProjectbudgetService;
import com.wysql.ascost.util.TestForExcel2PDF;
import com.wysql.ascost.util.UploadFileUtil;
import com.wysql.ascost.util.ZipUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 业务附件表Controller
 *
 * @author SQL
 * @ClassName: InfoFileController
 * @date 2023-06-06 23:07:07
 */
@Api(value = "业务附件表")
@Controller
@RequestMapping("/InfoFileController")
public class InfoFileController extends BaseController {

    private String prefix = "info/infoFile";

    @Autowired
    private InfoFileService infoFileService;

    @Autowired
    private UploadFileUtil fileUtil;

    @Value("${file.uploadUrl}")
    private String uploadPath;

    @Autowired
    private InfoProjectbudgetService infoProjectbudgetService;

    /**
     * 业务附件表页面展示
     *
     * @param model
     * @return String
     * @author SQL
     */
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/view")
    @RequiresPermissions("gen:infoFile:view")
    public String view(ModelMap model) {
        return prefix + "/list";
    }

    /**
     * list集合
     *
     * @param tablepar
     * @param
     * @return
     */
    //@Log(title = "业务附件表", action = "111")
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/list")
    @RequiresPermissions("gen:infoFile:list")
    @ResponseBody
    public ResultTable list(Tablepar tablepar, InfoFile infoFile) {
        PageInfo<InfoFile> page = infoFileService.list(tablepar, infoFile);
        return pageTable(page.getList(), page.getTotal());
    }

    /**
     * 新增跳转
     */
    @ApiOperation(value = "新增跳转", notes = "新增跳转")
    @GetMapping("/add")
    public String add(ModelMap modelMap) {
        return prefix + "/add";
    }

    /**
     * 新增保存
     *
     * @param
     * @return
     */
    //@Log(title = "业务附件表新增", action = "111")
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping("/add")
    @RequiresPermissions("gen:infoFile:add")
    @ResponseBody
    public AjaxResult add(InfoFile infoFile) {
        int b = infoFileService.insertSelective(infoFile);
        if (b > 0) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 业务附件表删除
     *
     * @param ids
     * @return
     */
    //@Log(title = "业务附件表删除", action = "111")
    @ApiOperation(value = "删除", notes = "删除")
    @DeleteMapping("/remove")
    @RequiresPermissions("gen:infoFile:remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        int b = infoFileService.deleteByPrimaryKey(ids);
        if (b > 0) {
            return success();
        } else {
            return error();
        }
    }


    /**
     * 修改跳转
     *
     * @param id
     * @param
     * @return
     */
    @ApiOperation(value = "修改跳转", notes = "修改跳转")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap map) {
        map.put("InfoFile", infoFileService.selectByPrimaryKey(id));

        return prefix + "/edit";
    }

    /**
     * 修改保存
     */
    //@Log(title = "业务附件表修改", action = "111")
    @ApiOperation(value = "修改保存", notes = "修改保存")
    @RequiresPermissions("gen:infoFile:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(InfoFile infoFile) {
        return toAjax(infoFileService.updateByPrimaryKeySelective(infoFile));
    }

    /**
     * 概算书文件补传跳转--针对手动新增
     */
    @ApiOperation(value = "概算书文件补传跳转--针对手动新增", notes = "概算书文件补传跳转--针对手动新增")
    @GetMapping("/uploadExcel/{id}/{step}")
    public String upload(@PathVariable("id") String id,@PathVariable("step") String step, ModelMap modelMap) {
//        InfoProjectbudget infoProjectbudget = infoProjectbudgetService.selectByPrimaryKey(id);
//        if ("1".equals(infoProjectbudget.getCreatetype())){
//
//        }
        //根据单据业务ID和行ID查询业务附件表中对应的附件信息
        InfoFileExample infoFileExample = new InfoFileExample();
        InfoFileExample.Criteria criteria = infoFileExample.createCriteria();
        criteria.andFkRecordEqualTo(id);
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        modelMap.put("infoFiles", infoFiles);
        modelMap.put("recordId", id);
        modelMap.put("step", step);
        return prefix + "/fileupload";
    }

    /**
     * PDF文件预览跳转
     */
    @ApiOperation(value = "PDF文件预览跳转", notes = "PDF文件预览跳转")
    @GetMapping("/fileview/{id}")
    public String fileview(@PathVariable("id") String id,ModelMap modelMap) {
        //根据单据业务ID和行ID查询业务附件表中对应的附件信息
        InfoFileExample infoFileExample = new InfoFileExample();
        InfoFileExample.Criteria criteria = infoFileExample.createCriteria();
        criteria.andFkRecordEqualTo(id);
        criteria.andSuffixEqualTo(".pdf");
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        modelMap.put("infoFiles", infoFiles);
        modelMap.put("recordId", id);
        return prefix + "/fileview";
    }

    /**
     * 支撑文件上传--源自taskDepScoreUpload
     *
     * @param file -
     * @return -
     */
    @RequestMapping(value = "/supportFileUpload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> supportFileUpload(@RequestParam("file") MultipartFile file,
                                                 @RequestParam("recordId") String recordId,
                                                 @RequestParam("folderName") String folderName,
                                                 @RequestParam("fkSubject") String fkSubject,
                                                 @RequestParam("taskid") String taskid) {

        //Map<String, Object> msg = uploadFileUtil.uploadFile(file, folderName);
        Map<String, Object> msg = fileUtil.uploadFile2(file, folderName);
        System.err.println(msg);
        String code = msg.get("code").toString();
        Map<String, Object> map = new HashMap<>();
        if (code.equals("0")) {
            String fileUrl = msg.get("fileUrl").toString();
            String fileName = msg.get("fileName").toString();
            String localPath = msg.get("localPath").toString();
            map.put("code", 0);
            map.put("msg", "上传成功");
            map.put("fileUrl", fileUrl);
            map.put("fileName", fileName);
            map.put("localPath", localPath);
            //上传成功后记录附件信息至业务附件表
            InfoFile infoFile = new InfoFile();
            infoFile.setId(UUID.randomUUID().toString());
            infoFile.setLocationPath(localPath);
            infoFile.setFileUrl(fileUrl);
            infoFile.setFileSize(Integer.valueOf(msg.get("size").toString()));
            infoFile.setFileName(fileName);
            infoFile.setFkSubject(fkSubject);
            infoFile.setFkRecord(recordId);
            if (fkSubject.equals("3")) {
                infoFile.setFkTaskId(taskid);
            }
            infoFile.setSuffix(fileName.substring(fileName.lastIndexOf(".")));
            infoFile.setCreateDate(new Date());
            infoFileService.insertSelective(infoFile);
        } else {
            map.put("code", 1);
            map.put("msg", "上传失败，请重试或联系管理员");
            map.put("fileUrl", "");
            map.put("fileName", "");
            map.put("localPath", "");
        }
        return map;
    }

    /**
     * 手动新增数据概算书文件上传
     *
     * @param file -
     * @return -
     */
    @RequestMapping(value = "/excelFileUpload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> excelFileUpload(@RequestParam("file") MultipartFile file,
                                                 @RequestParam("recordId") String recordId,
                                                 @RequestParam("step") String step,
                                                 @RequestParam("folderName") String folderName) {
        Map<String, Object> map = new HashMap<>();
        //校验一：判断该概算书已上传文件个数，已经上传的不允许上传多个
        InfoFileExample infoFileExample = new InfoFileExample();
        infoFileExample.createCriteria().andFkRecordEqualTo(recordId).andSuffixEqualTo(".pdf");
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        if (infoFiles!=null && infoFiles.size()>0){
            map.put("code", 1);
            map.put("msg", "上传失败，一个概算书只允许上传一个附件");
            return map;
        }

        //Todo 校验二：判断上传文件名称是否已经存在--严谨的话应该判断Excel中封面名称
        InfoFileExample infoFileExample1 = new InfoFileExample();
        infoFileExample1.createCriteria().andRealNameEqualTo(file.getOriginalFilename()).andFkTaskIdEqualTo(step);
        List<InfoFile> infoFiles1 = infoFileService.selectByExample(infoFileExample1);
        if (infoFiles1!=null && infoFiles1.size()>0){
            map.put("code", 1);
            map.put("msg", "上传失败，该概算书与之前上传概算书文件名称同名，请检查校验");
            return map;
        }

        //Map<String, Object> msg = uploadFileUtil.uploadFile(file, folderName);
        Map<String, Object> msg = fileUtil.uploadFile2(file, folderName);
        System.err.println(msg);
        String code = msg.get("code").toString();

        if (code.equals("0")) {
            String fileUrl = msg.get("fileUrl").toString();
            String fileName = msg.get("fileName").toString();
            String localPath = msg.get("localPath").toString();
            map.put("code", 0);
            map.put("msg", "上传成功");
            map.put("fileUrl", fileUrl);
            map.put("fileName", fileName);
            map.put("localPath", localPath);
            //上传成功后记录附件信息至业务附件表
            InfoFile infoFile = new InfoFile();
            infoFile.setId(UUID.randomUUID().toString());
            infoFile.setLocationPath(localPath);
            infoFile.setFileUrl(fileUrl);
            infoFile.setFileSize(Integer.valueOf(msg.get("size").toString()));
            infoFile.setFileName(fileName);
            infoFile.setSuffix(fileName.substring(fileName.lastIndexOf(".")));
            infoFile.setCreateDate(new Date());
            infoFile.setFkRecord(recordId);
            infoFile.setRealName(fileName);
            infoFile.setFkTaskId(step);
            infoFileService.insertSelective(infoFile);

            //Excel转换为PDF上传至服务器文件夹
            TestForExcel2PDF.excel2pdf(localPath,localPath.replaceAll(".xlsx",".pdf").replaceAll(".xls",".pdf").replaceAll("#","号"));

            //上传成功后记录附件信息至业务附件表
            InfoFile infoFile1 = new InfoFile();
            infoFile1.setId(UUID.randomUUID().toString());
            infoFile1.setLocationPath(localPath.replaceAll(".xlsx",".pdf").replaceAll(".xls",".pdf").replaceAll("#","号"));
            infoFile1.setFileUrl(fileUrl.replaceAll(".xlsx",".pdf").replaceAll(".xls",".pdf").replaceAll("#","号"));
//            infoFile1.setFileSize(Integer.valueOf(msg.get("size").toString()));
            infoFile1.setFileName(fileName.replaceAll(".xlsx",".pdf").replaceAll(".xls",".pdf"));
            infoFile1.setSuffix(".pdf");
            infoFile1.setCreateDate(new Date());
            infoFile1.setFkRecord(recordId);
            infoFile1.setFkTaskId(step);
            infoFileService.insertSelective(infoFile1);


        } else {
            map.put("code", 1);
            map.put("msg", "上传失败，请重试或联系管理员");
            map.put("fileUrl", "");
            map.put("fileName", "");
            map.put("localPath", "");
        }
        return map;
    }

    /**
     * 根据业务单据行ID获取业务文件
     *
     * @param
     * @return
     */
    @RequestMapping("/getFilebyRecordId")
    @ResponseBody
    public Map<String, Object> getFilebyRecordId(InfoFile infoFile) {
        Map<String, Object> map = new HashMap<>();
        InfoFileExample infoFileExample = new InfoFileExample();
        InfoFileExample.Criteria criteria = infoFileExample.createCriteria();
        criteria.andFkRecordEqualTo(infoFile.getFkRecord());
//        criteria.andFkSubjectEqualTo(infoFile.getFkSubject());
//        if (infoFile.getFkSubject().equals("3")) {
//            criteria.andFkTaskIdEqualTo(infoFile.getFkTaskId());
//        }
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        map.put("listFiles", infoFiles);
        return map;
    }

    /**
     * 根据文件ID删除业务文件
     *
     * @param
     * @return
     */
    @RequestMapping("/delInfoFile")
    @ResponseBody
    public Map<String, Object> delInfoFile(InfoFile infoFile) {
        Map<String, Object> map = new HashMap<>();
        int del = infoFileService.deleteByPrimaryKey(infoFile.getId());
        if (del > 0) {
//            uploadFileUtil.deleteFile(uploadUrl + evidenceDetails.getLocalPath());
            map.put("code", 200);
            map.put("msg", "删除成功");
        } else {
            map.put("code", 500);
            map.put("msg", "删除失败，请重试");
        }
        return map;
    }

    /**
     * 根据文件ID删除业务文件
     *
     * @param
     * @return
     */
    @RequestMapping("/delFilebyRecordId")
    @ResponseBody
    public Map<String, Object> delFilebyRecordId(InfoFile infoFile) {
        Map<String, Object> map = new HashMap<>();

        InfoFileExample infoFileExample = new InfoFileExample();
        infoFileExample.createCriteria().andFkRecordEqualTo(infoFile.getFkRecord());
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        for (InfoFile file : infoFiles) {
            int del = infoFileService.deleteByPrimaryKey(file.getId());
            if (del <= 0) {
                map.put("code", 500);
                map.put("msg", "删除失败，请重试");
                return map;
            }
        }
        map.put("code", 200);
        map.put("msg", "删除成功");
        return map;
    }

    /**
     * 上传佐证文件跳转
     */
    @ApiOperation(value = "上传佐证文件跳转", notes = "上传佐证文件跳转")
    @GetMapping("/proofupload/{id}/{fkSubject}/{taskid}")
    public String proofupload(@PathVariable("id") String id, @PathVariable("fkSubject") String fkSubject, @PathVariable("taskid") String taskid, ModelMap modelMap) {
        //根据单据业务ID和行ID查询业务附件表中对应的附件信息
        InfoFileExample infoFileExample = new InfoFileExample();
        InfoFileExample.Criteria criteria = infoFileExample.createCriteria();
        criteria.andFkRecordEqualTo(id);
        criteria.andFkSubjectEqualTo(fkSubject);
        if (fkSubject.equals("3")) {
            criteria.andFkTaskIdEqualTo(taskid);
        }
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        modelMap.put("infoFiles", infoFiles);
        modelMap.put("recordId", id);
        modelMap.put("fkSubject", fkSubject);
        modelMap.put("taskid", taskid);
        return prefix + "/proofupload";
    }

    /**
     * 查看佐证文件跳转（历史佐证双页签）
     */
    @ApiOperation(value = "查看佐证文件跳转（历史佐证双页签）", notes = "查看佐证文件跳转（历史佐证双页签）")
    @GetMapping("/proofview/{id}/{fkSubject}/{taskid}")
    public String proofview(@PathVariable("id") String id, @PathVariable("fkSubject") String fkSubject, @PathVariable("taskid") String taskid, ModelMap modelMap) {
        //根据单据业务ID和行ID查询业务附件表中对应的附件信息
        InfoFileExample infoFileExample = new InfoFileExample();
        InfoFileExample.Criteria criteria = infoFileExample.createCriteria();
        criteria.andFkRecordEqualTo(id);
        criteria.andFkSubjectEqualTo(fkSubject);
        if (fkSubject.equals("3")) {
            criteria.andFkTaskIdEqualTo(taskid);
        }
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        modelMap.put("infoFiles", infoFiles);
        modelMap.put("recordId", id);
        modelMap.put("fkSubject", fkSubject);
        modelMap.put("taskid", taskid);
        return prefix + "/proofview";
    }


    /**
     * 批量下载附件
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量下载附件", notes = "批量下载附件")
    @GetMapping("/batchdownload/{ids}")
    public void batchdownload(@PathVariable("ids") String ids) {
        List idsList = Arrays.asList(ids.split(","));
        InfoFileExample infoFileExample = new InfoFileExample();
        infoFileExample.createCriteria().andIdIn(idsList);
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        List<String> paths = new ArrayList<>();
        for (InfoFile infoFile : infoFiles) {
            paths.add(infoFile.getLocationPath());
        }
        long l = System.currentTimeMillis();
        String zipFileName = "佐证批量下载"+String.valueOf(l)+".zip";
        try {
            ZipUtil.zipDownload(response, paths, zipFileName, uploadPath + zipFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 模板文件下载跳转
     */
    @ApiOperation(value = "模板文件下载跳转", notes = "模板文件下载跳转")
    @GetMapping("/templatedownload/{id}")
    public String templatedownload(@PathVariable("id") String id,ModelMap modelMap) {
        //根据单据业务ID和行ID查询业务附件表中对应的附件信息
        InfoFileExample infoFileExample = new InfoFileExample();
        InfoFileExample.Criteria criteria = infoFileExample.createCriteria();
        criteria.andFkRecordEqualTo(id);
//        criteria.andSuffixEqualTo(".xlsx");
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        modelMap.put("infoFiles", infoFiles);
        modelMap.put("recordId", id);
        return prefix + "/templatedownload";
    }

    /**
     * 查询模板文件list（根据四级编码和taskid）
     *
     * @param
     * @param
     * @return
     */
    //@Log(title = "业务附件表", action = "111")
    @ApiOperation(value = "查询佐证历史list（根据四级编码和taskid）", notes = "查询佐证历史list（根据四级编码和taskid）")
    @GetMapping("/templateList/{recordId}")
    @ResponseBody
    public ResultTable templateList(@PathVariable("recordId") String recordId, Tablepar tablepar, InfoFile infoFile) {
        PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
        InfoFileExample infoFileExample = new InfoFileExample();
//        infoFileExample.createCriteria().andFkSubjectEqualTo("2").andFkRecordEqualTo(recordId);
        infoFileExample.createCriteria().andFkRecordEqualTo(recordId);
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        PageInfo<InfoFile> pageInfo = new PageInfo<InfoFile>(infoFiles);
        return pageTable(pageInfo.getList(), pageInfo.getTotal());
    }


    /**
     * 上传模板文件跳转
     */
    @ApiOperation(value = "上传文件跳转", notes = "上传文件跳转")
    @GetMapping("/uploadTemplate/{id}/{fkSubject}")
    public String uploadTemplate(@PathVariable("id") String id, @PathVariable("fkSubject") String fkSubject,ModelMap modelMap) {
        //根据单据业务ID和行ID查询业务附件表中对应的附件信息
        InfoFileExample infoFileExample = new InfoFileExample();
        InfoFileExample.Criteria criteria = infoFileExample.createCriteria();
        criteria.andFkRecordEqualTo(id);
        criteria.andFkSubjectEqualTo(fkSubject);
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        modelMap.put("infoFiles", infoFiles);
        modelMap.put("recordId", id);
        modelMap.put("fkSubject", fkSubject);
        return prefix + "/templateupload";
    }

    /**
     * 下载单个文件（不压缩）
     *
     * @param ids
     * @return
     */
    //@Log(title = "业务附件表删除", action = "111")
    @ApiOperation(value = "下载单个文件（不压缩）", notes = "下载单个文件（不压缩）")
    @GetMapping("/downloadsingle/{id}")
    public void downloadsingle(@PathVariable("id") String ids) {
        List idsList = Arrays.asList(ids.split(","));
        InfoFileExample infoFileExample = new InfoFileExample();
        infoFileExample.createCriteria().andIdIn(idsList);
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        String path = null;
        for (InfoFile infoFile : infoFiles) {
            path = infoFile.getLocationPath();
        }
        try {
            UploadFileUtil.downLoad(response,path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询对应佐证文件是否存在
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "更新月度必备项目自评价结果", notes = "更新月度必备项目自评价结果")
    @PostMapping("/proofexist")
    @ResponseBody
    public AjaxResult proofcount(@RequestBody InfoFile infofile) {
        int result = 0;
        InfoFileExample infoFileExample = new InfoFileExample();
        infoFileExample.createCriteria().andFkRecordEqualTo(infofile.getFkRecord()).andFkTaskIdEqualTo(infofile.getFkTaskId());
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        if (infoFiles!=null && infoFiles.size()>0){
            result = 1;
        }
        return AjaxResult.successData(200,result);
    }

    /**
     * 预览佐证文件图片
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "更新月度必备项目自评价结果", notes = "更新月度必备项目自评价结果")
    @GetMapping("/upload/pic")
    public String pic(String e, ModelMap modelMap) {
        System.err.println(e);
        modelMap.put("e", e);
        return prefix + "/pic";
    }

    /**
     * 根据recordid下载单个文件（不压缩）
     *
     * @param recordid
     * @return
     */
    //@Log(title = "业务附件表删除", action = "111")
    @ApiOperation(value = "根据recordid下载单个文件（不压缩）", notes = "根据recordid下载单个文件（不压缩）")
    @GetMapping("/downloadbyrecordid/{recordid}")
    public void downloadbyrecordid(@PathVariable("recordid") String recordid) {
        InfoFileExample infoFileExample = new InfoFileExample();
        infoFileExample.createCriteria().andFkRecordEqualTo(recordid);
        List<InfoFile> infoFiles = infoFileService.selectByExample(infoFileExample);
        String path = null;
        for (InfoFile infoFile : infoFiles) {
            path = infoFile.getLocationPath();
        }
        try {
            UploadFileUtil.downLoad(response,path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
